﻿using System;
using System.Collections.Generic;
using System.Data;
using BLL;
using ET;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class Quotes : System.Web.UI.UserControl
    {
        private readonly Quotes_BLL clsQuotes = new Quotes_BLL();

        #region Event
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetData();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsCurrency();
            }
        }
        //-------Store-Datasource-----------------
        protected void StoreQuotes_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetData();
        }
        protected void StoreQuotesMaterials_RefreshData(object sender, StoreReadDataEventArgs e)
        {

        }
        protected void StoreQuotesProvision_RefreshData(object sender, StoreReadDataEventArgs e)
        {

        }
        protected void StoreMaterials_RefreshData(object sender, StoreReadDataEventArgs e)
        {

        }
        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            txtQuotes_ID.Text = string.Empty;
            GetComboBox();
            ClearTextBox();
            Quotes_Product_BLL.Deletetb_Quotes_Product_Default(-1);
            GetQuotes_Materials_User();
            GetQuotes_Provision();
            WindowsQuotes.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grQuotes.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    GetComboBox();
                    ClearTextBox();
                    DataDetail(int.Parse(row.RecordID));
                    GetQuotes_Materials();
                    GetQuotes_Provision();
                    Sum();
                    WindowsQuotes.Show();
                    sm.UpdateSelection();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grQuotes.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    try
                    {
                        Quotes_BLL.Deletetb_Quotes(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetData();
        }
        protected void btnDelProduct_Click(object sender, DirectEventArgs e)
        {
            var sm = grQuotesMaterials.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    try
                    {
                        Quotes_Product_BLL.Deletetb_Quotes_Product(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            if (txtQuotes_ID.Text != null)
            {
                GetQuotes_Materials();
            }
            else
            {
                GetQuotes_Materials_User();
            }
            Sum();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtQuotes_ID.Text == string.Empty)
            {
                try
                {
                    if (!CheckInsert())
                    {
                        var obj = new Quotes_ET
                        {
                            Quotes_No = txtQuotes_No.Text,
                            Quotes_Time = DateTime.Parse(txtQuotes_Time.Text),
                            Customer_ID = int.Parse(txtCustomer_ID.Text),
                            Quotes_UnitPrice = float.Parse(txtSumPrice.Text.Replace(".", "")),
                            Quotes_VAT = float.Parse(txtSumVAT.Text.Replace(".", "")),
                            Quotes_ShippingFee = float.Parse(txtShippingFee.Text.Replace(".", "")),
                            Quotes_TotalCash = float.Parse(txtSumTotalCash.Text.Replace(".", "")),
                            Currency_ID = int.Parse(cbCurrency.SelectedItem.Value),
                            Quotes_Date_Add = DateTime.Now,
                            Quotes_Computer_Add = Environment.MachineName
                        };
                        bool Save = Quotes_BLL.Inserttb_Quotes(obj);
                        if (Save)
                        {
                            string json = e.ExtraParams["Quotes_Provision"];
                            if (string.IsNullOrEmpty(json))
                            {
                                return;
                            }
                            var ProvisionAll = JSON.Deserialize<List<Quotes_Provision_ET>>(json);

                            foreach (Quotes_Provision_ET p in ProvisionAll)
                            {
                                var insert = new Quotes_Provision_ET
                                {
                                    Quotes_Provision_Name = p.Quotes_Provision_Name,
                                    Quotes_Provision_Value = p.Quotes_Provision_Value,
                                    Quotes_ID = obj.Quotes_ID
                                };
                                Quotes_Provision_BLL.Inserttb_Quotes_Provision(insert);
                            }
                            HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công ! ");
                            GetData();
                            GetQuotes_Materials_User();
                            GetQuotes_Provision();
                            GetComboBox();
                            ClearTextBox();
                        }
                    }
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
                }
            }
            else
            {
                try
                {
                    if (CheckPermisstionDobclick())
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                    }
                    else
                    {
                        if (!CheckInsert())
                        {
                            var obj = new Quotes_ET
                            {
                                Quotes_ID = int.Parse(txtQuotes_ID.Text),
                                Quotes_No = txtQuotes_No.Text,
                                Quotes_Time = DateTime.Parse(txtQuotes_Time.Text),
                                Customer_ID = int.Parse(txtCustomer_ID.Text),
                                Quotes_UnitPrice = float.Parse(txtSumPrice.Text.Replace(".", "")),
                                Quotes_VAT = float.Parse(txtSumVAT.Text.Replace(".", "")),
                                Quotes_ShippingFee = float.Parse(txtShippingFee.Text.Replace(".", "")),
                                Quotes_TotalCash = float.Parse(txtSumTotalCash.Text.Replace(".", "")),
                                Currency_ID = int.Parse(cbCurrency.SelectedItem.Value),
                                Quotes_Date_Modify = DateTime.Now,
                                Quotes_Computer_Modify = Environment.MachineName
                            };
                            bool Save = Quotes_BLL.Updatetb_Quotes(obj);
                            if (Save)
                            {
                                Quotes_Provision_BLL.Deletetb_Quotes_Provision_DefaultID(int.Parse(txtQuotes_ID.Text));
                                string json = e.ExtraParams["Quotes_Provision"];
                                if (string.IsNullOrEmpty(json))
                                {
                                    return;
                                }
                                var ProvisionAll = JSON.Deserialize<List<Quotes_Provision_ET>>(json);

                                foreach (Quotes_Provision_ET p in ProvisionAll)
                                {
                                    var update = new Quotes_Provision_ET
                                    {
                                        Quotes_Provision_Name = p.Quotes_Provision_Name,
                                        Quotes_Provision_Value = p.Quotes_Provision_Value,
                                        Quotes_ID = int.Parse(txtQuotes_ID.Text)
                                    };
                                    Quotes_Provision_BLL.Inserttb_Quotes_Provision(update);
                                }
                                WindowsQuotes.Close();
                                HTML.clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                                GetData();
                                GetQuotes_Materials();
                                GetQuotes_Provision();
                                GetComboBox();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
                }
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsQuotes.Close();
        }
        protected void btnAddQuotesMaterials_Click(object sender, DirectEventArgs e)
        {
            GetMaterials();
            WindowMaterials.Show();
        }
        //----------Click-------------------
        protected void QuotesDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Quotes_ID = int.Parse(e.ExtraParams["Quotes_ID"]);
            DataDetail(Quotes_ID);
            GetQuotes_Materials();
            GetQuotes_Provision();
            Sum();
            WindowsQuotes.Show();
        }
        protected void UpdateMaterials_Click(object sender, DirectEventArgs e)
        {
            string json = e.ExtraParams["Quotes_Materials"];
            if (string.IsNullOrEmpty(json))
            {
                return;
            }
            var Quotes_Materials = JSON.Deserialize<List<Quotes_Product_ET>>(json);

            foreach (Quotes_Product_ET p in Quotes_Materials)
            {
                var update = new Quotes_Product_ET
                {
                    Quotes_Materials_ID = p.Quotes_Materials_ID,
                    Materials_Id = p.Materials_Id,
                    Quotes_Product_Quantity = p.Quotes_Product_Quantity,
                    Quotes_Product_Price = p.Quotes_Product_Price,
                    Quotes_Product_VAT_Percent = p.Quotes_Product_VAT_Percent,
                    Quotes_Product_VAT = p.Quotes_Product_Quantity * p.Quotes_Product_Price * p.Quotes_Product_VAT_Percent / 100,
                    Quotes_Product_TotalCash = p.Quotes_Product_Quantity * p.Quotes_Product_Price + (p.Quotes_Product_Quantity * p.Quotes_Product_Price * p.Quotes_Product_VAT_Percent / 100),
                    Quotes_ID = txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text),
                    User_ID = int.Parse(Session["Users_Id"].ToString())
                };
                Quotes_Product_BLL.Updatetb_Quotes_Product(update);
            }
            Sum();
            if (txtQuotes_ID.Text == String.Empty)
            {
                GetQuotes_Materials_User();
            }
            else
            {
                GetQuotes_Materials();
            }
            GetQuotes_Provision();
        }
        protected void btnSelectMaterials_Click(object sender, DirectEventArgs e)
        {
            var sm = grMaterials.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                if (!CheckInsertMaterials(row.RecordID, txtQuotes_ID.Text == string.Empty ? "-1" : txtQuotes_ID.Text))
                {
                    var obj = new Quotes_Product_ET
                    {
                        Materials_Id = int.Parse(row.RecordID),
                        Quotes_ID = txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text),
                        User_ID = int.Parse(Session["Users_Id"].ToString())
                    };
                    Quotes_Product_BLL.Inserttb_Quotes_Product(obj);
                    HTML.clsFormat.Alert_INFO("Thông báo", "Thêm sản phẩm thành công !");
                }
            }
            GetQuotes_Materials_User();
            WindowMaterials.Hide();
            CheckboxSelectionModel1.ClearSelection();
        }
        //----------Button-Windows--------------- 
        #endregion
        #region[Method]
        protected void GetData()
        {
            DataTable dtQuotes = clsQuotes.BindGirdtb_Quotes(string.Empty);
            if (dtQuotes != null && dtQuotes.Rows.Count > 0)
            {
                StoreQuotes.DataSource = dtQuotes;
                StoreQuotes.DataBind();
            }
        }
        protected void GetMaterials()
        {
            var clsMaterials = new Materials_BLL();
            DataTable dtMaterials = clsMaterials.GetMaterials();
            if (dtMaterials != null && dtMaterials.Rows.Count > 0)
            {
                StoreMaterials.DataSource = dtMaterials;
                StoreMaterials.DataBind();
            }
        }
        protected void GetQuotes_Materials()
        {
            var clsQuotes_Product = new Quotes_Product_BLL();
            DataTable dtQuotes_Product = clsQuotes_Product.BindGirdtb_Quotes_Product(int.Parse(txtQuotes_ID.Text));
            if (dtQuotes_Product != null)
            {
                StoreQuotesMaterials.DataSource = dtQuotes_Product;
                StoreQuotesMaterials.DataBind();
            }
        }
        protected void GetQuotes_Materials_User()
        {
            var clsQuotes_Product = new Quotes_Product_BLL();
            DataTable dtQuotes_Product = clsQuotes_Product.BindGirdtb_Quotes_Product_User(txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text), int.Parse(Session["Users_Id"].ToString()));
            if (dtQuotes_Product != null)
            {
                StoreQuotesMaterials.DataSource = dtQuotes_Product;
                StoreQuotesMaterials.DataBind();
            }
        }
        protected void GetQuotes_Provision()
        {
            var clsQuotesProvision = new Quotes_Provision_BLL();
            DataTable dtQuotesProvision = clsQuotesProvision.BindGirdtb_Quotes_Provision(txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text));
            if (dtQuotesProvision != null && dtQuotesProvision.Rows.Count > 0)
            {
                StoreQuotesProvision.DataSource = dtQuotesProvision;
                StoreQuotesProvision.DataBind();
            }
        }
        protected void DataDetail(int id)
        {
            DataTable dtQuotes = clsQuotes.BindGirdtb_QuotesDetail(id);
            if (dtQuotes != null && dtQuotes.Rows.Count > 0)
            {
                txtQuotes_ID.Text = dtQuotes.Rows[0]["Quotes_ID"].ToString();
                txtQuotes_No.Text = dtQuotes.Rows[0]["Quotes_No"].ToString();
                txtQuotes_Time.Text = dtQuotes.Rows[0]["Quotes_Time"].ToString();
                txtCustomer_Name.Text = dtQuotes.Rows[0]["Customer_Name"].ToString();
                txtCustomer_Address.Text = dtQuotes.Rows[0]["Customer_Address"].ToString();
                txtCustomer_Contact.Text = dtQuotes.Rows[0]["Contact_Name"].ToString();
                txtCustomer_Job.Text = dtQuotes.Rows[0]["Job_Name"].ToString();
                txtSumPrice.Text = dtQuotes.Rows[0]["Quotes_UnitPrice"].ToString();
                txtSumVAT.Text = dtQuotes.Rows[0]["Quotes_VAT"].ToString();
                txtShippingFee.Text = dtQuotes.Rows[0]["Quotes_ShippingFee"].ToString();
                txtSumTotalCash.Text = dtQuotes.Rows[0]["Quotes_TotalCash"].ToString();
                cbCurrency.SetValue(int.Parse(dtQuotes.Rows[0]["Currency_ID"].ToString()));
            }
        }
        public void Sum()
        {
            var cls = new Quotes_Product_BLL();
            DataTable dtSum = cls.SumQuotes(txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text));
            if (dtSum != null && dtSum.Rows.Count > 0)
            {
                txtSumPrice.Text = dtSum.Rows[0]["SumPrice"].ToString() == "" ? "0" : String.Format("{0:0,00}", dtSum.Rows[0]["SumPrice"]);
                txtSumVAT.Text = dtSum.Rows[0]["SumVAT"].ToString() == "" ? "0" : String.Format("{0:0,00}", dtSum.Rows[0]["SumVAT"]);
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var Quotes = new Quotes_BLL();
            var dtQuotes = Quotes.BindGirdtb_Quotes(string.Empty);
            var Quotes_Product = new Quotes_Product_BLL();
            var dtQuotes_Product = Quotes_Product.BindGirdtb_Quotes_Product(txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text));
            if (dtQuotes != null && dtQuotes.Rows.Count > 0)
            {
                foreach (DataRow dr in dtQuotes.Rows)
                {
                    if (txtQuotes_ID.Text != dr["Quotes_ID"].ToString())
                    {
                        if (txtQuotes_No.Text == dr["Quotes_No"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã báo giá đã tồn tại !");
                        }
                    }
                }
            }
            if (dtQuotes_Product.Rows.Count == 0)
            {
                kiemtra = true;
                HTML.clsFormat.Alert_ERROR("Thông Báo", "Vui lòng thêm sản phẩm báo giá !");
            }
            return kiemtra;
        }
        protected bool CheckInsertMaterials(string a, string b)
        {
            bool kiemtra = false;
            var clsQuotes_Product = new Quotes_Product_BLL();
            DataTable dtQuotes_Product = clsQuotes_Product.BindGirdtb_Quotes_Product(txtQuotes_ID.Text == string.Empty ? -1 : int.Parse(txtQuotes_ID.Text));
            if (dtQuotes_Product != null && dtQuotes_Product.Rows.Count > 0)
            {
                foreach (DataRow dr in dtQuotes_Product.Rows)
                {
                    if (a == dr["Materials_ID"].ToString() && dr["Quotes_ID"].ToString() == b)
                    {
                        kiemtra = true;
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Mặt hàng này đã có vui lòng cập nhật lại !");
                    }
                }
            }
            return kiemtra;
        }
        #endregion
        #region [ComboBox]
        protected void GetComboBox()
        {
            var clsCurrency = new Currency_BLL();
            DataTable dtCurrency = clsCurrency.BindGirdtb_Currency(string.Empty);
            if (dtCurrency != null && dtCurrency.Rows.Count > 0)
            {
                CurrencyStore.DataSource = dtCurrency;
                CurrencyStore.DataBind();
            }
        }
        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }
        #endregion
        #region[ClearTextbox]
        protected void ClearTextBox()
        {
            FormPanelQuotes.Reset();
            txtQuotes_No.Text = MaTuDong();
            txtQuotes_Time.Text = DateTime.Now.ToShortDateString();
        }
        #endregion
        #region[MaTangTuDong]
        protected string MaTuDong()
        {
            int i;
            DataTable dt = clsQuotes.BindGirdtb_Quotes(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Quotes_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Quotes_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Quotes_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "BG_00" + i;
        }
        #endregion
        #region[Search]
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtQuotes = clsQuotes.BindGirdtb_Quotes(txtSearch.Text);
            if (dtQuotes != null && dtQuotes.Rows.Count > 0)
            {
                StoreQuotes.DataSource = dtQuotes;
                StoreQuotes.DataBind();
            }
        }
        protected void SearchMaterials_Event(object sender, DirectEventArgs e)
        {
            var clsMaterials = new Materials_BLL();
            DataTable dtMaterials = clsMaterials.Search(txtSearchMaterials.Text);
            if (dtMaterials != null && dtMaterials.Rows.Count > 0)
            {
                StoreMaterials.DataSource = dtMaterials;
                StoreMaterials.DataBind();
            }
        }
        #endregion
        #region Customer
        protected void GetCustomer()
        {
            var clsCustomer = new Customer_BLL();
            DataTable dtCustomer = clsCustomer.BindGirdtb_Customer(txtSearchQuotesCustomer.Text);
            if (dtCustomer != null && dtCustomer.Rows.Count > 0)
            {
                StoreQuotesCustomer.DataSource = dtCustomer;
                StoreQuotesCustomer.DataBind();
            }
            else
            {
                grQuotesCustomer.GetStore().RemoveAll();
            }
        }
        protected void btnCustomer_Click(object sender, DirectEventArgs e)
        {
            GetCustomer();
            WindowQuotesCustomer.Show();
        }
        protected void StoreQuotesCustomer_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            StoreQuotesCustomer.Reload();
        }

        protected void CellQuotesCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grQuotesCustomer.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                string id = sm.SelectedCell.RecordID;
                var clsCustomer = new Customer_BLL();
                DataTable dtCustomer = clsCustomer.GetCustomerDetail(int.Parse(id));
                txtCustomer_ID.Text = dtCustomer.Rows[0]["Customer_ID"].ToString();
                txtCustomer.Text = dtCustomer.Rows[0]["Customer_Alias"].ToString();
                txtCustomer_Name.Text = dtCustomer.Rows[0]["Customer_Name"].ToString();
                txtCustomer_Address.Text = dtCustomer.Rows[0]["Customer_Address"].ToString();
                txtCustomer_Contact.Text = dtCustomer.Rows[0]["Contact_Name"].ToString();
                txtCustomer_Job.Text = dtCustomer.Rows[0]["Job_Name"].ToString();
                sm.Clear();
                sm.UpdateSelection();
                WindowQuotesCustomer.Close();
            }
        }
        protected void SearchQuotesCustomer_Event(object sender, DirectEventArgs e)
        {
            GetCustomer();
        }
        #endregion
        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Quotes, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelQuotes.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Quotes, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        private void WindowsCurrency()
        {
            Window win = new Window()
            {
                ID = "WindowsCurrency",
                Title = "Tiền tệ",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Currency.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}